﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FantasyBlog.DAL;
using System.Data.Entity;

namespace FantasyBlog.BLL
{
    public abstract class AbstractMetadataProvider<TEntity> where TEntity:class,new()
    {
        public AbstractMetadataProvider(string MetasetName)
        {
            object value=null;
            var property = model.GetType().GetProperty(MetasetName);
            if (property == null)
                throw new Exception("Metadata set does not find in DbContext");
            value = property.GetValue(model,null);
            if(value is DbSet<TEntity>)
            {
                if(typeof(TEntity).GetProperty("Key")==null
                    || typeof(TEntity).GetProperty("Value")==null)
                    throw new Exception("Metadata set does not Contains Key & Value property");
                metaset = value as DbSet<TEntity>;
                Load();
            }
            else
                throw new Exception("Metadata set does not find in DbContext");

        }
        public string this[string Key]
        {
            get{
                if (metadata.ContainsKey(Key))
                    return metadata[Key];
                return string.Empty;
            }
            set
            {
                dynamic entry = metaset.Find(Key);
                if (entry != null)
                {
                    entry.Value = value;
                }
                else
                {
                    dynamic newEntry = new TEntity();
                    newEntry.Key = Key;
                    newEntry.Value=value;
                    metaset.Add(newEntry);
                }
                model.SaveChanges();
                if (metadata.ContainsKey(Key))
                    metadata[Key] = value;
                else
                    metadata.Add(Key, value);
            }
        }

        public void Remove(string Key)
        {
            var entry = metaset.Find(Key);
            if (entry != null)
                metaset.Remove(entry);
            model.SaveChanges();
            if (metadata.ContainsKey(Key))
                metadata.Remove(Key);
        }
        public void Load()
        {
            foreach (dynamic entity in metaset)
            {
                metadata.Add(entity.Key.Trim(), entity.Value.Trim());
            }
        }
        protected DbSet<TEntity> metaset = null;
        protected BlogModelContainer model = new BlogModelContainer();
        protected Dictionary<string,string> metadata = new   Dictionary<string,string>();
    }
}
